package com.snopy.socket;



import java.io.*;
import java.net.*;


/**
 * @author snopy
 * @version 1.0.0
 * @classname Demo2
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/10 10:16
 */
public class SocketService {

    public static void main(String[] args) throws IOException {

        try {
            //1.创建新的套接字socket
            ServerSocket socket = new ServerSocket();
            socket.bind(new InetSocketAddress(80));

            //socket = new ServerSocket(80);
            while (true) {
                System.out.println("正在监听------");
                Socket accept = socket.accept();
                System.out.println("监听到一个客户端请求");
                System.out.println("为该客户端创建一个线程实列并开始运行该线程");
                serviceThread thread1 = new serviceThread(accept);
                thread1.start();
            }
        }catch (Exception e){

        }



    }

}
class serviceThread extends Thread {
    private Socket socket;


    public serviceThread(Socket t_socket) {
        socket = t_socket;
    }

    @Override
    public void run() {
        System.out.println("线程开始，打印该客户端的ip和端口");
        System.out.println(socket.getLocalSocketAddress() + ": " + socket.getLocalPort());
        InputStream clientInput = null;
        InputStreamReader clientInputStream = null;
        BufferedReader clientBufferReader = null;
        OutputStream clientOutStream = null;
        Writer clientWriter = null;
        System.out.println("打印该客户端的请求报文头");
        try {
            clientBufferReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String st = null;
            while ((st = clientBufferReader.readLine()) != null && st.length() != 0) {
                System.out.println(st);

                //System.out.println(st.substring(st.indexOf(":")));
            }

            socket.shutdownInput();
            //System.out.println("构造回应报文头并发送给还客户端");
            clientWriter = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
            /*
            * 状态码
            * 200 成功,web服务器成功处理客户端请求
            * 301 永久重定向,当客户端请求一个网址的时候,Web服务器会将当前请求重定向到另一个网址,搜索引擎
            * */
            clientWriter.write("HTTP/1.2 200 OK\r\n");
            //clientWriter.write("Transfer-Encoding: chunked\r\n");
            clientWriter.write("Content-Type: text/html;charset=UTF-8\r\n");
            clientWriter.write("\r\n");

            clientWriter.write("<HTML>\r\n");
            clientWriter.write("<HEAD><TITLE>hello world</TITLE></HEAD>\r\n");
            clientWriter.write("<body><h1 style='color:red'>你好</h1></body>\r\n");
            clientWriter.write("</HTML>\r\n");
            clientWriter.flush();
            socket.close();

        } catch (Exception e) {

        }

    }
}